package com.cjm.ry.jvm.nio.charnio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.*;

public class GroupChatClient2 {
    private Selector selector;
    private List<SocketChannel> socketChannelList = new ArrayList<>(10);
    Map<String, SocketChannel> socketMap = new HashMap<>(10);

    public GroupChatClient2() throws IOException {
        this.selector = Selector.open();

        for (int i = 0; i < 10; i++) {
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 9999));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            String userName = socketChannel.getLocalAddress().toString().substring(1) + socketChannel.hashCode();
            System.out.println(userName + "is ok~");
            socketChannelList.add(socketChannel);
            socketMap.put(userName, socketChannel);
        }


    }
    // 发送消息
    private void sendMsg(String msg) throws IOException {
        for (SocketChannel channel : socketChannelList) {
            String tmsg = socketMap.get(channel.hashCode()) + " 说：" + msg;
            channel.write(ByteBuffer.wrap(msg.getBytes()));
        }
    }

    private void readMsg() throws IOException {

        int count = selector.select();
        if (count > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer);
                    System.out.println(socketChannel.hashCode() + " , 接收到服务端的消息: "+new String(byteBuffer.array()));
                }
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        GroupChatClient2 chatClient = new GroupChatClient2();
        new Thread(() -> {
            while (true) {
                try {
                    chatClient.readMsg();
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            chatClient.sendMsg(msg);
        }
    }

}
